/* $RCSFile: PrivateDocCsvFeeder.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.EMailing/PageModules/DownloadSession/PrivateDocCsvFeeder.ascx.cs $
 * $log$
 * Revision 23 2010/08/09 11:12:45  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 10 2010/08/09 10:13:18  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;

using AddonNice.CRMEMailing;
using AddonNice.CRMEMailing.Settings.UI.WebControls;
using AddonNice.Settings.CRMEMailing;
using AddonNice.CRMWrapper.CRMEMailing;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.DownloadSession
{
 	/// <summary>
    /// Initializer class for PrivateDocCsvFeeder 
    /// </summary>
    public class PrivateDocCsvFeederSI : PrivateDocFeeder0SI
    {
        public PrivateDocCsvFeederSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base(bSettings,pm)
        {
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocCsvFeederSI Ctor BEG.",PrivateDocFeederTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocCsvFeederSI Ctor END.",PrivateDocFeederTrace.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocCsvFeederSI InitSettings BEG.",PrivateDocFeederTrace.Sw.Info);
            
            base.InitSettings(bSettings,pm);


            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocCsvFeederSI InitSettings END.",PrivateDocFeederTrace.Sw.Info);
        }
 
    }

    /// <summary>
    /// From a folder, a campaign, a marketinglist read documents in a folder and generates privateDocuments entities related to current campaign
    /// Also fill a table to accelerate the sending of bulk emails referencing privatedocuments, as we need to send the private document id for each mail we will access them with the the sessionid, the listuserid
    /// </summary>
    public partial class PrivateDocCsvFeeder : PrivateDocFeeder0
    {

        #region General implementation
        
        public override Guid GuidID
        {
            get
            {
                return new Guid(AStr.PrivateDocCsvFeederGuid);
            }
        }
        #endregion General implementation

        
        public PrivateDocCsvFeeder()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocCsvFeeder Ctor Called.",ModuleTraceSwitch.Sw.Info);
            // Validators : name Ok
            ValidationGroup                     =   "Main";

        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "PRIVATEDOCCSVFEEDER";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new PrivateDocCsvFeederSI(bSettings,this);
        }

    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose | PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocCsvFeeder Page_Load isPostBack: {0}",IsPostBack),(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:PrivateDocFeederTrace.Sw.Info);
            const string fmt                        =   "realPostBack('{0}', ''); return false;";
            updateBtn.OnClientClick                 =   string.Format(fmt, updateBtn.UniqueID);
            if (!IsPostBack)
            {
            }
        }

        DataTable loadCsv(string path2)
        {

            DataTable data = new DataTable();
            if ( File.Exists(path2) )
            {
                // Open the file to read from.
                using ( StreamReader sr = File.OpenText(path2) )
                {
                    // Parse the line
                    string s = string.Empty;
                    string[] dataValues;
                    DataColumn col;

                    // Do the following to add schema.
                    dataValues = sr.ReadLine().Split(',');
                    // For each token in the comma-delimited string, add a column
                    // to the DataTable schema.
                    foreach ( string token in dataValues )
                    {
                        col = new DataColumn(token,typeof(string));
                        data.Columns.Add(col);
                    }

                    // Do the following to add data.
                    while ( ( s = sr.ReadLine() ) != null )
                    {
                        dataValues = s.Split(',');
                        data.Rows.Add(CopyRowData(dataValues,data.NewRow()));
                    }
                }
                data.AcceptChanges();
            }
            return data;
        }

        private DataRow CopyRowData(string[] source, DataRow target) 
        {
            try {
                for (int i = 0;i < source.Length;i++) {
                    target[i] = source[i];
                }
            }
            catch (System.IndexOutOfRangeException) {
                // There are more columns in this row than
                // the original schema allows.  Stop copying
                // and return the DataRow.
                return target;
            }
            return target;
        }

        /*
         * Columns for csv file Format
         * <Title />
         * <FileName />
         * <FileUrl />
         * <SchemaName />
         * <ID />
         * <Name />
         */
        void FillFromCsv(Guid SessionId)
        {
            string path                         =   ImportFileName.Text;
            DataTable Tb                        =   loadCsv(path);

            foreach ( DataRow rw in Tb.Rows )
            {
                string title       =   (string)rw["Title"];
                string filename    =   (string)rw["Filename"];
                string fileurl     =   (string)rw["FileUrl"];
                string schema      =   (string)rw["SchemaName"];
                string id          =   (rw["ID"] != DBNull.Value ) ? (string)rw["ID"]:string.Empty;
                string name        =   (string)rw["Name"];
                bool created       =   false;
                if ( File.Exists(fileurl) )
                {
                    InternalQueryExpression qe  =   new InternalQueryExpression();
                    qe.ColumnSet                =   new InternalAllColumns();
                    qe.EntityName               =   AStr.adnprivatedocument;
                    qe.Criteria                 =   new InternalFilterExpression();
                    InternalConditionExpression ce =   new InternalConditionExpression();
                    if ( id != string.Empty )
                    {
                        switch ( schema )
                        {
                            case CrmStr.account:
                            ce.AttributeName = CrmStr.accountid;
                            break;
                            case CrmStr.contact:
                            ce.AttributeName = CrmStr.contactid;
                            break;
                            case CrmStr.lead:
                            ce.AttributeName = CrmStr.leadid;
                            break;
                        }
                        ce.Operator = InternalConditionOperator.Equal;
                        ce.Values = new string[] { id };
                    }
                    else
                    {
                        switch ( schema )
                        {
                            case CrmStr.account:
                            ce.AttributeName = CrmStr.name;
                            break;
                            case CrmStr.contact:
                            ce.AttributeName = CrmStr.fullname;
                            break;
                            case CrmStr.lead:
                            ce.AttributeName = CrmStr.fullname;
                            break;
                        }
                        ce.Operator = InternalConditionOperator.Equal;
                        ce.Values = new string[] { name };
                    }
                    InternalConditionExpression ce2 =   new InternalConditionExpression();
                    ce2.AttributeName           =   AStr.adndownloadsessionid;
                    ce2.Operator                =    InternalConditionOperator.Equal;
                    ce2.Values                  =   new string[] { SessionId.ToString()};
                    qe.Criteria.Conditions      =   new InternalConditionExpression[]{ce,ce2};
                    int count                   =   0;
                    ADNDynPrivateDocument priv  =   Wrapper.Util.FindEntityByQuery<ADNDynPrivateDocument>(AStr.adnprivatedocument,qe,ResetWrapper,ref count,true,null);
                    if ( priv == null )
                    {
                        priv                    =   new ADNDynPrivateDocument(ResetWrapper,title);
                        priv.adnfilename        =   filename;
                        ADNDynCustomer dynCust  =   null;
                        int cnt                 =   0;
                        switch ( schema )
                        {
                            case CrmStr.account:
                            if ( id != string.Empty )
                                dynCust         =   DynEntity.GetFromCache<ADNDynAccount>(CrmStr.account,Wrapper,ResetWrapper,new Guid(id));
                            else dynCust        =   Wrapper.Util.FindAccountByName(name,false,ref created);
                            break;
                            case CrmStr.contact:
                            if ( id != string.Empty )
                                dynCust         =   DynEntity.GetFromCache<ADNDynContact>(CrmStr.contact,Wrapper,ResetWrapper,new Guid(id));
                            else dynCust        =   Wrapper.Util.FindEntityByStringField<ADNDynContact>(CrmStr.contact,CrmStr.fullname,name,ResetWrapper,ref cnt,true,null);
                            break;
                            case CrmStr.lead:
                            if ( id != string.Empty )
                                dynCust         =   DynEntity.GetFromCache<ADNDynLead>(CrmStr.lead,Wrapper,ResetWrapper,new Guid(id));
                            else dynCust        =   Wrapper.Util.FindEntityByStringField<ADNDynLead>(CrmStr.lead,CrmStr.fullname,name,ResetWrapper,ref cnt,true,null);
                            break;
                        }
                        if ( dynCust != null )
                            switch ( schema )
                            {
                                case CrmStr.account:
                                priv.adnaccountid    =   dynCust.PrimaryKeyGuidValue;
                                break;
                                case CrmStr.contact:
                                priv.adncontactid   =   dynCust.PrimaryKeyGuidValue;
                                break;
                                case CrmStr.lead:
                                priv.adnleadid      =   dynCust.PrimaryKeyGuidValue;
                                break;
                            }
                        priv.adncategory        =   1;
                        priv.adnfileurl         =   fileurl;
                        priv.adndownloadsessionid   =   SessionId;
                        priv.adndownloadcount   =   0;
                        priv.Create();
                        created                 =   true;
                    }
                    LoadFile(priv,fileurl,title,filename,created);
                }
            }
        }


        void PrivateDocCsvFeeder_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            // Should Email contain values
            if (!Page.IsValid)
            {
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( "[V]PrivateDocCsvFeeder PrivateDocCsvFeeder_ADNUpdateModule : Page not valid",PrivateDocFeederTrace.Sw.Info);
                return;
            }

            if ( string.IsNullOrEmpty(CbDownloadSession.SelectedValue) )
                return;

            // Update or Add new entity to Crm
            try
            {
                Guid DwnSessionId       =   new Guid(CbDownloadSession.SelectedValue);
                FillFromCsv(DwnSessionId);
            }
            catch (Exception ex)
            {
                if (PrivateDocFeederTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDocCsvFeeder PrivateDocCsvFeeder_ADNUpdateModule  ex: {0}", ex),PrivateDocFeederTrace.Sw.Info);
                throw;
            }
        }

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            updateBtn.SkinID        =   "Update_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            BtnChooseFile.SkinID    =   "Open_"+ Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                                        +=  new System.EventHandler(Page_Load);
            ADNUpdateModule                             +=  new PortalModuleEventHandler(PrivateDocCsvFeeder_ADNUpdateModule);
            CbDownloadSession.WebServiceSettings.Method =   "GetDownloadSessions";
            CbDownloadSession.WebServiceSettings.Path   =   "/Services/XrmEmailing.asmx";

            CbDownloadSession.WebServiceMethod          =   "GetDownloadSessions";
            CbDownloadSession.WebServicePath            =   "/Services/XrmEmailing.asmx";
        }

        #endregion Std overrides
    }
}